#include <iostream>
using namespace std;

#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>

/*互斥锁*/
pthread_mutex_t g_mutet;
/*信号量*/
sem_t g_sem;

/*打印机公共资源*/
void printfer(const char *str)
{
    /*加锁 减一 P操作*/
    sem_wait(&g_sem);
    while (*str != '\0')
    {
        putchar(*str);
        fflush(stdout);
        str++;
        sleep(1);
    }
    /*解锁 加一 V操作*/
    sem_post(&g_sem);
}
/*线程回调函数*/
void *thread_func1(void *arg)
{
    /*加锁*/
    pthread_mutex_lock(&g_mutet);
    /*线程分离*/
    pthread_detach(pthread_self());

    const char *str = "helloworld.";
    printfer(str);
    /*解锁*/
    pthread_mutex_unlock(&g_mutet);

    /*线程退出*/
    pthread_exit(NULL);
}

void *thread_func2(void *arg)
{
    /*加锁*/
    pthread_mutex_lock(&g_mutet);
    /*线程分离*/
    pthread_detach(pthread_self());

    const char *str = "STM32F429IGT6.";
    printfer(str);
    /*解锁*/
    pthread_mutex_unlock(&g_mutet);

    /*线程退出*/
    pthread_exit(NULL);
}

int main(int argc, char const *argv[])
{
#if 0
    /*初始化🔒*/
    pthread_mutex_init(&g_mutet,NULL);
#endif

    /*初始化信号量*/
    sem_init(&g_sem, 0, 1);
    /*创建线程*/
    pthread_t tid1;
    int ret = pthread_create(&tid1, NULL, thread_func1, NULL);
    if (ret != 0)
    {
        perror("thread create error.");
        _exit(-1);
    }

    pthread_t tid2;
    ret = pthread_create(&tid2, NULL, thread_func2, NULL);
    if (ret != 0)
    {
        perror("thread create error.");
        _exit(-1);
    }

    int cnt = 50;
    while (cnt--)
    {
        sleep(1);
    }
#if 0
    pthread_mutex_destroy(&g_mutet);
#endif
    sem_destroy(&g_sem);
    return 0;
}
